<script setup lang="ts">
import { loginAPI } from "@/apis/user";
import router from "@/router";
import { useUserStore } from "@/stores/user";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { ref } from "vue";

// 登录时提交的数据
interface Login {
  mobile: string;
  code: string;
  isChecked: boolean;
}
const formData = ref<Login>({
  mobile: "13200000000",
  code: "246810",
  isChecked: true,
});

// 表单验证
const formRules = ref<FormRules<Login>>({
  mobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { pattern: /^\d{6}$/, message: "请输入6位数字验证码" },
  ],
  isChecked: [
    { required: true, message: "请勾选协议", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        if (value) {
          callback();
        } else {
          callback(new Error("请阅读并同意用户协议和隐私条款,并勾选"));
        }
      },
      trigger: "change",
    },
  ],
});

// 获取 store
const store = useUserStore();

const formRef = ref<FormInstance>();

const submit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      const res = await loginAPI(formData.value);
      // console.log(res.data.token)
      // 调用 store 的方法保存 token
      store.setToken(res.data.token);
      // 跳转到首页
      router.push("/");
      // 轻提示
      ElMessage.success("登录成功");
    }
  });
};
</script>

<template>
  <div class="container">
    <el-card>
      <img class="logo" src="@/assets/images/logo.png" alt="" />
      <!-- 表单 -->
      <el-form :rules="formRules" :model="formData" ref="formRef">
        <el-form-item prop="mobile" label="手机号">
          <el-input
            placeholder="请输入手机号"
            v-model="formData.mobile"
          ></el-input>
        </el-form-item>

        <el-form-item prop="code" label="验证码">
          <el-input
            placeholder="请输入验证码"
            v-model="formData.code"
          ></el-input>
        </el-form-item>

        <el-form-item prop="isChecked">
          <el-checkbox :value="true" v-model="formData.isChecked"
            >我已阅读并同意「用户协议」和「隐私条款」</el-checkbox
          >
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submit">登 录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<style lang="less" scoped>
.container {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  background: url("@/assets/images/login.png");

  .el-card {
    width: 440px;
    height: 380px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    box-shadow: 0 0 50px rgba(0, 0, 0, 0.1);

    .logo {
      width: 200px;
      display: block;
      margin: 0 auto 20px;
    }
  }
  .el-form {
    padding: 0 20px;
    .el-button {
      width: 100%;
    }
  }
}
</style>
